package com.example.chatweb.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.chatweb.service.KnowledgeBaseService;
import com.example.chatweb.utils.HttpUtil;
import com.example.chatweb.utils.MyExceptionHandler;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

//import static sun.java2d.xr.XRUtils.None;

@Service
@Slf4j
public class KnowledgeBaseServiceImpl implements KnowledgeBaseService {
	
	
	@Autowired
	private HttpUtil httpUtil;
	
	@Override
	public void createKnowledgeBase(String knowledge_base_name) {
		
		try {
			// 先检查该知识库是否已经存在
			String preFixUrl = "http://10.112.203.120:7861/knowledge_base";
			String listHubUrl = preFixUrl + "/list_knowledge_bases";
			// TODO: 发送GET请求获取文件列表
			JSONObject response = httpUtil.get(listHubUrl, null);
			// 判断正确返回
			if (response.getInteger("code") != 200) {
				throw new MyExceptionHandler("连接问答知识库错误：无法查询知识库列表");
			}
			// 获取列表
			JSONArray hubBases = response.getJSONArray("data");
			// 变为List<String>
			List<String> hubBaseList = new ArrayList<>();
			for (int i = 0; i < hubBases.size(); i++) {
				hubBaseList.add(hubBases.getString(i));
			}
			// 判断是否存在
			if (!hubBaseList.contains(knowledge_base_name)) {
				//	不存在才创建
				
				String createHubUrl = preFixUrl + "/create_knowledge_base";
				Map<String, Object> requestBody = new HashMap<>();
				requestBody.put("knowledge_base_name", knowledge_base_name);
				requestBody.put("vector_store_type", "faiss");
				requestBody.put("embed_model", "bge-large-zh-v1.5");
				response = httpUtil.post(createHubUrl, requestBody);
				if (response.getInteger("code") != 200) {
					throw new MyExceptionHandler("创建知识库错误：" + response.getString("msg"));
				}
			}
		} catch (Exception e) {
			log.error("连接问答知识库错误：" + e.getMessage(), e);
			throw new MyExceptionHandler("连接问答知识库错误：" + e.getMessage());
		}
		
	}
	
	@Override
	public void addFileToKnowledgeBase(String url, String knowledge_base_name) {
		// 下载文件
		byte[] file = null;
		try {
			file = httpUtil.getFile(url);
		} catch (Exception e) {
			throw new MyExceptionHandler("下载静态文件时出现错误");
		}
		if (file == null) {
			throw new MyExceptionHandler("下载静态文件时出现错误");
		}
		// 根据url解析文件名称，取最后一个/后的字符串
		String[] temp = url.split("/");
		String fileName = temp[temp.length - 1];
		
		String postUrl = "http://10.112.203.120:7861/knowledge_base/upload_docs";
		try {
			Map<String, Object> formData = new HashMap<>();
			formData.put("knowledge_base_name", knowledge_base_name);
			JSONObject response = httpUtil.postFileAndFormData(postUrl, file, fileName, formData);
			if (response.getInteger("code") != 200) {
				throw new MyExceptionHandler(
				 "上传文件到知识库时出现错误：" + response.getString("msg"));
			}
		} catch (Exception e) {
			throw new MyExceptionHandler("向量化文件时出现错误");
		}
	}

//    @Override
//    public List<String> KnowledgeBaselist(){
//        String url = "http://10.112.203.120:7861/knowledge_base/list_knowledge_bases";
//        JSONObject requestBody = new JSONObject();
//        JSONObject response = httpUtil.get(url);
//        System.out.println(response);
//        List<String> knowledgeBases = new ArrayList<>();
//        if (response != null) {
//            // 检查响应码是否为 200，这意味着请求成功
//            if (response.getInteger("code") == 200) {
//                JSONArray dataArray = response.getJSONArray("data");
//                if (dataArray != null) {
//                    for (int i = 0; i < dataArray.size(); i++) {
//                        knowledgeBases.add(dataArray.getString(i));
//                    }
//                } else {
//                    System.out.println("No data available");
//                }
//            } else {
//                System.out.println("Failed to retrieve knowledge bases: " + response.getString("msg"));
//            }
//        } else {
//            System.out.println("Response is null");
//        }
//        return knowledgeBases;
//    }
}
